package com.example.vueblog.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import com.example.vueblog.common.RedisConstants;
import com.example.vueblog.common.utils.IdUtils;
import com.example.vueblog.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yushunshun
 * @date 2022/7/21 1:12
 */
@Service
public class CaptchaService {

    @Autowired
    RedisUtils redisUtils;

    /**
     * 验证码生成
     *
     * @return
     */
    public Map<String, String> generateVerifyCode() {
        Map<String, String> result = new HashMap<>();
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        //CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);
        //图形验证码写出，可以写出到文件，也可以写出到流
        //captcha.write("d:/circle.png");
        //验证图形验证码的有效性，返回boolean值
//        captcha.verify("1234");
        //将生成的眼眸图形写入流中
        FastByteArrayOutputStream out = new FastByteArrayOutputStream();
        captcha.write(out);

        //获取验证码 并组合redis的key
        String code = captcha.getCode();
        String uuid = IdUtils.simpleUUID();
        String key = RedisConstants.VERIFY_CODE + uuid;
        redisUtils.set(key, code,10);
        //获取base64
        String encode = Base64.encode(out.toByteArray());
        result.put("encode", encode);
        result.put("uuid", uuid);
        result.put("code", captcha.getCode());
        return result;
    }
}
